package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service        //将实现类交给ioc容器
@Transactional      //增加事务管理器
public class CategoryControllerImpl implements CategoryService {

    //依赖注入mapper层接口
    @Autowired
    private CategoryMapper categoryMapper;

    //查询分类模块
    @Override
    public List<Category> findAll() {
        //调用mapper层
        return categoryMapper.findAll();
    }

    //添加分类
    @Override
    public void save(Category category) {
        //1. 补全分类信息
        //1-1 使用雪花算法,创建id生成器
        long id = IdUtil.getSnowflake(1, 1).nextId();
        //1-2 添加id信息
        category.setId(id);
        /*//1-3 添加创建/更新时间
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        //1-4 添加创建/更新人
        category.setCreateUser(1L);
        category.setUpdateUser(1L);*/

        //2.调用mapper层
        categoryMapper.save(category);
    }

    //修改分类
    @Override
    public void updateById(Category category) {
        //1.补充分类信息
        //1-1 添加修改人/时间
        //category.setUpdateUser(1L);
        //category.setUpdateTime(new Date());

        //2.调用mapper层
        categoryMapper.updateById(category);
    }

    //删除分类
    @Override
    public void deleteById(Long id) {
        //1.业务处理
        //1-1 根据id查询dish表中菜品的数目
        Long dishSum = categoryMapper.countDishByCategoryId(id);
        //判断数目是否为空
        if (dishSum > 0) {
            //若不空,则无法删除
            throw new CustomException("操作失败:此菜名正在被使用...");
        }
        //1-2 根据id查询setmeal表中套餐的数目
        Long setmealSum = categoryMapper.countSetmealByCategoryId(id);
        //判断数目是否为空
        if (setmealSum > 0) {
            //若不空, 则无法删除
            throw new CustomException("操作失败:此套餐名正在被使用...");
        }

        //2.若上述条件都不满足,则调用mapper层
        categoryMapper.deleteById(id);

    }
}
